<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\model;

use buwang\base\BaseModel;
use buwang\traits\JwtTrait;
use buwang\service\MiniappService;

/**租户表
 * Class BwAuthNode
 * @package app\manage\model
 */
class Member extends BaseModel
{
    protected $pk = 'id';
    // 表名
    protected $name = 'Member';

    use JwtTrait;

    // 追加属性
    protected $append = [
        'sub_member_id',
    ];

    //子租户id
    public function getSubMemberIdAttr($value, $data)
    {
        if (isset($data['parent_id']) && $data['parent_id'] > 0 && isset($data['mobile'])) {
            return self::where('mobile', $data['mobile'])->value('id');
        } else {
            return 0;
        }
    }

    /*
     * 设置查询初始化条件
     * @param string $alias 表别名
     * @param object $model 模型实例化对象
     * @return object
     */
    public static function valiWhere($alias = '', $model = null)
    {
        $model = is_null($model) ? new self() : $model;
        if ($alias) {
            $model = $model->alias($alias);
        }
        return $model;
    }

    /** 根据输入密码得到 加密后的密码串和盐
     * @param $password
     * @return array
     */
    public static function getPassword($password, $salt = null)
    {

        if (!$salt) $salt = self::getSalt();
        $salt1 = md5($salt);
        $password = md5($password) . $salt1 . 'buwang';  //把密码进行md5加密然后和salt连接
        $password = md5($password);  //执行MD5散列
        $password = md5($password);  //执行MD5散列
        return compact('password', 'salt');  //返回散列
    }


    /** 根据输入密码得到 加密后的密码
     * @param $password
     * @return array
     */
    public static function getPasswordMD5($password)
    {
        return password_hash(md5($password), PASSWORD_DEFAULT);  //返回散列
    }

    public static function getSalt()
    {
        $salt = get_num_code(6);
        return $salt;
    }

    //添加子租户
    public static function createAdmin($param, $top_id, $trans = false, $is_admin = false, $is_register = false)
    {
        if (!isset($param['username']) || !$param['username']) return self::setError('用户名不存在');
        if (!isset($param['nickname']) || !$param['nickname']) return self::setError('昵称不存在');
        //if (!isset($param['mobile']) || !$param['mobile']) return self::setError('手机号不存在');
        if (isset($param['mobile'])) {
            if (!preg_match("/^[0-9]{11}$/", $param['mobile'])) return self::setError('手机号请使用11位数字');
            $admin = self::where('mobile', $param['mobile'])->find();
            if ($admin) return self::setError('手机号已存在');
        }
        if (!isset($param['safe_password']) || !$param['safe_password']) return self::setError('六位安全密码不存在');
        // if(!isset($param['email'])||!$param['email'])return self::setError('电子邮箱不存在');
        if (!preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)(?!\\W+$)[0-9A-Za-z\\W]{8,16}$/", $param['password'])) return self::setError('密码8-16位字符必须是（英文/数字/特殊符号）至少两种的组合');
        if (isset($param['password2'])) {
            if ($param['password2'] != $param['password']) return self::setError('两次输入的密码不一致');
            unset($param['password2']);
        }
        if (!preg_match("/^[a-zA-Z\d_]{5,}$/", $param['username'])) return self::setError('用户名请使至少5位不能带中文和特殊符号');
        if (!preg_match("/^[0-9]{6}$/", $param['safe_password'])) return self::setError('安全密码请使用6位数字');

        $admin = self::where('username', $param['username'])->find();
        if ($admin) return self::setError('用户名已存在');

        if (!$is_admin) {
            $top = self::getTop($top_id);
            if (!$top) return self::setError('顶级租户信息异常');
        }
        $register_top = false;//是否是注册顶级租户
        // var_dump($id);die;//常用函数
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = $res3 = $res4 = $res5 = $res6 = true;
        try {
            unset($param['id']);
            if (!$is_admin) {
                $param['parent_id'] = $top_id;
                $param['top_id'] = $top['id'];
            } else {
                $register_top = true;
                $param['parent_id'] = 0;
            }

            //创建账号
            //得到账号密码

            //加密得到密文和盐
//            $passinfo = self::getPassword($param['password']);
//            $param['password'] = $passinfo['password'];
//            $param['salt'] = $passinfo['salt'];
            //设置MD5密码
            $param['password'] = self::getPasswordMD5($param['password']);
            //设置安全密码
            $param['safe_password'] = self::getPasswordMD5($param['safe_password']);
            $res1 = self::create($param);

            if ($is_admin && $res1) {
                $data = self::find($res1['id']);
                $data['top_id'] = $data['id'];
                $res3 = $data->save();
            }
            if (!$is_register) {
                //更新角色
                $res2 = AuthGroupAccess::updateRule($res1['id'], explode(",", $param['rule_ids']), 'member', false);
            } else {
                //登录页注册分支
                //注册用户附带初始角色
                $res2 = AuthGroupAccess::memberInitRule($res1['id'], false);
                $register_top = true;
            }
            //TODO:顶级租户注册初始化数据(未完善)
            if ($register_top) {
                //注册时配置
                /**2020 07 22 配置懒加载 注释以下代码**/
                //插入所有的租户的非懒加载配置
                //得到所有的租户配置
                $configs = Config::where('member_id', 0)->where('lazy', 2)->where('scopes', 'member')->select()->toArray();
                $configData = array();
                //组装配置数据
                foreach ($configs as $config) {
                    $con = $config;
                    unset($con['id']);
                    $con['member_id'] = $res1['id'];
                    $configData[] = $con;
                }
                if ($configData) {
                    $configg = new Config;
                    $res4 = $configg->saveAll($configData);
                }
                //注册时组合数据
                //得到所有的租户组合数据
                $configGroupData = ConfigGroupData::where('member_id', 0)->where('scopes', 'member')->select()->toArray();
                $configGroupDataList = array();
                //组装配置数据
                foreach ($configGroupData as $groupData) {
                    $con = $groupData;
                    unset($con['id']);
                    $con['member_id'] = $res1['id'];
                    $configGroupDataList[] = $con;
                }
                if ($configGroupDataList) {
                    $configg = new ConfigGroupData;
                    $res5 = $configg->saveAll($configGroupDataList);
                }
                //注册时钱包数据
                $MemberWallet = new MemberWallet;
                $Wallet = array();
                $Wallet['member_id'] = $res1['id'];
                $Wallet['create_time'] = time();
                $res6 = $MemberWallet->save($Wallet);

            }

            $res = $res && $res1 && $res2 && $res3 && $res4 && $res5 && $res6 && true;
            if ($trans) {
                self::checkTrans($res);
            }
            if (!$res1) return self::setError('创建账号失败');
            if (!$res2) return self::setError(AuthGroupAccess::getError());
            if (!$res3) return self::setError('创建账号失败');
            if (!$res4) return self::setError('初始化配置失败');
            if (!$res5) return self::setError('初始化组合数据失败');
            if (!$res6) return self::setError('初始化钱包数据失败');
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            return self::setError($e->getMessage());
        }
        if (!$res) return self::setError('创建租户成功');

        return $res;

    }

    public static function updateAdmin($param, $trans = false)
    {
        if (isset($param['password'])) {
            if (!$param['password']) {
                unset($param['password']);
            } else {
                if (!preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)(?!\\W+$)[0-9A-Za-z\\W]{8,16}$/", $param['password'])) return self::setError('密码8-16位字符必须是（英文/数字/特殊符号）至少两种的组合');
                if (isset($param['password2'])) {
                    if ($param['password2'] != $param['password']) return self::setError('两次输入的密码不一致');
                    unset($param['password2']);
                }
            }
        }
        if (isset($param['username'])) {
            if (!preg_match("/^[a-zA-Z\d_]{5,}$/", $param['username'])) return self::setError('用户名请使至少5位不能带中文和特殊符号');
            $admin = self::where('username', $param['username'])->where('id', 'not in', $param['id'])->find();
            if ($admin) return self::setError('用户名已存在');
        }
        if (isset($param['mobile'])) {
            if (!preg_match("/^[0-9]{11}$/", $param['mobile'])) return self::setError('手机号请使用11位数字');
            $admin = self::where('mobile', $param['mobile'])->where('id', 'not in', $param['id'])->find();
            if ($admin) return self::setError('手机号已存在');
        }
        if (isset($param['safe_password'])) {
            if (!$param['safe_password']) {
                unset($param['safe_password']);
            } else {
                if (!preg_match("/^[0-9]{6}$/", $param['safe_password'])) return self::setError('安全密码请使用6位数字');
            }
        }

        if (isset($param['nickname']) && !$param['nickname']) return self::setError('昵称不存在');
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = true;
        try {
            //加密得到密文和盐
            if (isset($param['password'])) {
                $param['password'] = self::getPasswordMD5($param['password']);
            }
            if (isset($param['safe_password'])) {
                $param['safe_password'] = self::getPasswordMD5($param['safe_password']);
            }

            $res1 = self::update($param);
            //更新角色
            isset($param['rule_ids']) && $res2 = AuthGroupAccess::updateRule($param['id'], explode(",", $param['rule_ids']), 'member', false);

            $res = $res && $res1 && $res2 && true;
            if ($trans) {
                self::checkTrans($res);
            }
            if (!$res1) return self::setError('更新账号失败');
            if (!$res2) return self::setError('更新角色失败');
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            return self::setError($e->getMessage());
        }
        if (!$res) return self::setError('更新租户失败');

        return $param;

    }


    /*// 获取菜单列表
    public static function getMenuList($admin_id, $dir = '', $miniapp_id = 0)
    {
        //顶级租户查询全部拥有的权限
        $admin = self::find($admin_id);
        if (!$admin) return [];
        //如果被禁用则返回
        if ($admin['is_lock']) return [];
        //得到用户所用角色
        $groupids = AuthGroupAccess::valiWhere()->where('uid', $admin_id)->where('scopes', 'member')->column('group_id');
        if (!$groupids) return [];
        //得到有效的角色
        $group_valid_ids = AuthGroup::where('id', 'in', $groupids)->where('status', 1)->where('scopes', 'member')->column('id');
        if (!$group_valid_ids) return [];
        //得到角色所有的权限
        $node_ids = AuthGroupNode::valiWhere()->where('group_id', 'in', $group_valid_ids)->column('node_id');
        if (!$node_ids) return [];
        //根据传递目录名获取应用菜单
        $where_app = $dir ? "type <> 'app' OR (type = 'app' AND app_name = '{$dir}')" : "type <> 'app'";
        $menuList = AuthNode::field('id,pid,menu_path as href,title,icon,target,param, type,app_name')
            ->where($where_app)
            ->where('id', 'in', $node_ids)
            ->where('status', 1)
            ->where('ismenu', 1)
            ->where('target', 'in', ['_self', '_blank', '_parent', '_top', ''])
            ->order('sort desc, id desc')
            ->select()
            ->toArray();
        if (!$menuList) return [];
        //组合数据
        $dir_pid = 0;
        foreach ($menuList as $i => &$node) {
            //有参数的拼参数
            if ($node['param']) $node['href'] .= '?' . $node['param'];
            unset($menuList[$i]['param']);
            if ($dir && $node['pid'] === 0 && $node['type'] === 'app' && $node['app_name'] === $dir) {
                $dir_pid = $node['id'];
            }
        }
        if ($dir_pid) {
            $id = time();
            $dir_menu = [
                ["pid" => $dir_pid, "id" => $pid = $id++, "href" => "", "title" => "应用设置", "icon" => "fa fa-gear", "target" => "_self", "type" => "app", "app_name" => "{$dir}",],
                ["id" => $id++, "pid" => $pid, "href" => "/manage/member.wechatKeyword/index?miniapp_id={$miniapp_id}", "title" => "回复规则管理", "icon" => "fa fa-paint-brush", "target" => "_self", "type" => "app", "app_name" => "{$dir}"],
                ["id" => $id++, "pid" => $pid, "href" => "/manage/member.official/index?miniapp_id={$miniapp_id}", "title" => "公众号菜单", "icon" => "fa fa-wechat", "target" => "_self", "type" => "app", "app_name" => "{$dir}"],
                ["id" => $id++, "pid" => $pid, "href" => "/manage/member.setting/index?miniapp_id={$miniapp_id}", "title" => "关于应用", "icon" => "fa fa-cubes", "target" => "_self", "type" => "app", "app_name" => "{$dir}"],
                ["id" => $id++, "pid" => $pid, "href" => "/manage/member.WechatKeyword/subscribe?miniapp_id={$miniapp_id}", "title" => "关注回复配置", "icon" => "fa fa-wechat", "target" => "_self", "type" => "system", "app_name" => "manage"],
                ["id" => $id++, "pid" => $pid, "href" => "/manage/member.wechatKeyword/materialList?miniapp_id={$miniapp_id}", "title" => "微信图文管理", "icon" => "fa fa-weixin", "target" => "_self", "type" => "app", "app_name" => "{$dir}"]
            ];
            $menuList = array_merge($menuList, $dir_menu);
        }
        $menuList = self::buildMenuChild(0, $menuList);
        return $menuList;
    }*/
    /**
     * @param array $admin 租户信息
     * @param string $miniapp_dir 获取系统菜单时传递 manage ,获取应用菜单时传递应用目录名
     * @return array|array[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getMenuList($admin, $miniapp_dir)
    {
        !$miniapp_dir && $miniapp_dir = $admin['default_miniapp_dir'];//未传递应用目录时获取默认应用
        $miniapp_type = $miniapp_dir === 'manage' ? 'system' : 'app';

        //菜单固定页
        $homeInfo = ['title' => bw_config('member_top_title'), 'href' => bw_config('member_top_url'),];
        //左上角
        $logoImage = '/layui/images/logo.png';
        isset($admin['avatar']) && $admin['avatar'] && $logoImage = $admin['avatar'];
        $logoInfo = ['title' => $admin['nickname'], 'image' => $logoImage, 'href' => '/'];
        //菜单列表
        $menuInfo = [];
        //得到查询条件
        $node_model = AuthNode::memberAuthWhere($admin, $miniapp_type, 'member', $miniapp_dir);
        if (!$node_model) return [$homeInfo, $logoInfo, $menuInfo];
        $nodes = $node_model->field('id,pid,menu_path as href,title,icon,target,param, type,app_name')
            ->order('sort desc, id desc')
//            ->fetchSql(true)
            ->select()
            ->toArray();

        if (!$nodes) return [$homeInfo, $logoInfo, $menuInfo];
        //组合数据
        foreach ($nodes as $i => &$node) {
            //有参数的拼参数
            if ($node['param']) $node['href'] .= '?' . $node['param'];
            unset($node['param']);
        }
        //为租户设置菜单固定页和添加微信管理菜单
        if ($miniapp_type === 'app') {
            //租户需拥有该应用
            $member_miniapp = \app\common\model\MemberMiniapp::withJoin('miniapp')->where([['member_miniapp.member_id', '=', $admin['id']], ['miniapp.dir', '=', $miniapp_dir]])->findOrEmpty()->toArray();
            if (!$member_miniapp) return [$homeInfo, $logoInfo, $menuInfo];
            $member_miniapp_id = $member_miniapp['id'];
            //判断应用到期状态
            MiniappService::checkMiniappExpire($member_miniapp); //校验应用是否过期
            //获取应用菜单根节点id
            $miniapp_menu_root_id = 0;
            array_walk($nodes, function (&$node) use ($member_miniapp, &$miniapp_menu_root_id) {
                //将应用根节点名称修改为租户应用自定义名称
                $node['pid'] === 0 && ($miniapp_menu_root_id = $node['id']) && ($node['title'] = $member_miniapp['appname']);
            });

            $id = time();
            //给租户应用设置微信管理
            $nodes_settings = [   //2021/4/29 给应用设置插件中心
                ["pid" => $miniapp_menu_root_id, "id" => $pid = $id++, "href" => "/manage/member/plugin/core/index?app={$miniapp_dir}", "title" => "插件中心", "icon" => "fa fa-gamepad", "target" => "_self", "type" => "app", "app_name" => $miniapp_dir,],
                ["pid" => $miniapp_menu_root_id, "id" => $pid = $id++, "href" => "", "title" => "应用设置", "icon" => "fa fa-gear", "target" => "_self", "type" => "app", "app_name" => $miniapp_dir,],
                ["id" => $id++, "pid" => $pid, "href" => "/manage/member.wechatKeyword/index?miniapp_id={$member_miniapp_id}", "title" => "回复规则管理", "icon" => "fa fa-paint-brush", "target" => "_self", "type" => "app", "app_name" => $miniapp_dir],
                ["id" => $id++, "pid" => $pid, "href" => "/manage/member.official/index?miniapp_id={$member_miniapp_id}", "title" => "公众号菜单", "icon" => "fa fa-wechat", "target" => "_self", "type" => "app", "app_name" => $miniapp_dir],
                ["id" => $id++, "pid" => $pid, "href" => "/manage/member.WechatKeyword/subscribe?miniapp_id={$member_miniapp_id}", "title" => "关注回复配置", "icon" => "fa fa-wechat", "target" => "_self", "type" => "system", "app_name" => "manage"],
                ["id" => $id++, "pid" => $pid, "href" => "/manage/member.wechatKeyword/materialList?miniapp_id={$member_miniapp_id}", "title" => "微信图文管理", "icon" => "fa fa-weixin", "target" => "_self", "type" => "app", "app_name" => $miniapp_dir]
            ];
            //应用接入小程序后可查看小程序订阅消息
            $member_miniapp['miniapp_appid'] && $nodes_settings[] = ["id" => $id++, "pid" => $pid, "href" => "/manage/member/wechat/message/template/index?miniapp_id={$member_miniapp_id}", "title" => "订阅消息", "icon" => "fa fa-weixin", "target" => "_self", "type" => "app", "app_name" => $miniapp_dir];
            $member_miniapp['miniapp_appid'] && $nodes_settings[] = ["id" => $id++, "pid" => $pid, "href" => "/manage/member/wechat/message/messageLog/index?miniapp_id={$member_miniapp_id}", "title" => "订阅消息发送记录", "icon" => "fa fa-weixin", "target" => "_self", "type" => "app", "app_name" => $miniapp_dir];
            //合并应用菜单和应用设置菜单
            $nodes = array_merge($nodes, $nodes_settings);

            //将应用首页设置为关于应用页面
            $homeInfo = ['title' => '应用主页', 'href' => "/manage/member.setting/index?miniapp_id={$member_miniapp_id}"];
        }
        $menuInfo = self::buildMenuChild(0, $nodes);

        return [$homeInfo, $logoInfo, $menuInfo];
    }

    //递归获取子菜单
    public static function buildMenuChild($pid, $menuList)
    {
        $treeList = [];
        foreach ($menuList as $v) {
            if ($pid == $v['pid']) {
                $node = $v;
                $child = self::buildMenuChild($v['id'], $menuList);
                if (!empty($child)) {
                    $node['child'] = $child;
                    $node['href'] = '';//存在子菜单则父级无url
                }
                // todo 后续此处加上用户的权限判断
                $treeList[] = $node;
            }
        }
        return $treeList;
    }


    /**判断登录密码是否正确
     * @param $mobile
     * @param $password
     */
    public static function validateMember($mobile, $password)
    {
        //判断用户是否存在
        $admin = self::where('mobile', $mobile)->find();

        if (!$admin) return self::setError('用户名或密码错误');
        if ($admin['status'] == 0) return self::setError('账号已被封禁无法登陆');
        //得到加密后的密码
//        $passWordInfo = self::getPassword($password,$admin['salt']);
//
//        if($admin['password']!=$passWordInfo['password'])return self::setError('用户名或密码错误');

        if (!self::checkPassword($password, $admin['password'])) return self::setError('用户名或密码错误');
        //查询用户组
        $group_ids = AuthGroupAccess::where('uid', $admin['id'])->where('scopes', 'member')->column('group_id');
        $admin['group_id'] = implode(",", $group_ids);//数组合并成字符串
        return $admin;
    }


    public static function loginMember($admin, $trans = false)
    {
        if ($trans) self::startTrans();
        $res = $res1 = $res2 = $tokenInfo = true;
        try {
            $data = [
                'id' => $admin['id'],
                'nickname' => $admin['nickname'],
                'mobile ' => $admin['mobile'] ?: '',
            ];
            $tokenInfo = self::getAccessToken($data, 'member');
            //有token就更新，不存在则存儲token
            //$res2 = Token::updateToken($admin['id'], $tokenInfo['token'], 'member');
            //更新用户登录信息
//            $admin->logintime = time();
//            $admin->loginip = request()->ip();
//            $res1 = $admin->save();
            $res1 = self::update(['login_time' => time(), 'login_ip' => get_real_ip()], ['id' => $admin['id']]);

            $res = $res1 && $res2 && $tokenInfo && true;
            if ($trans) self::checkTrans($res);
        } catch (\Exception $e) {
            if ($trans) self::rollback();
            return self::setError($e->getMessage());
        }
        if (!$tokenInfo) return self::setError('获取AccessToken或存储失败');
        if (!$res2) return self::setError('更新用户验证信息失败');
        if (!$res) return self::setError('更新用户登录信息失败');
        return $tokenInfo;

    }


    /**
     * 得到顶级租户
     */
    public static function getTop($member_id)
    {

        $member = self::find($member_id);
        if (!$member) {
            return self::setError('租户ID:' . $member_id . '的租户不存在');
        }
        if ($member['parent_id'] == 0) {
            return $member;
        } else {
            return self::getTop($member['parent_id']);
        }
    }


    public static function checkPassword($password, $safePassword)
    {
        //TODO：验证安全密码
        if (password_verify(md5($password), $safePassword)) {
            return true;
        } else {
            return false;
        }
    }


    /**更新密码
     * @param $param
     * @param bool $trans
     * @return mixed
     */
    public static function updatePassword($param, $trans = false)
    {
        if (isset($param['password'])) {
            if (!$param['password']) {
                unset($param['password']);
            } else {
                if (!preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)(?!\\W+$)[0-9A-Za-z\\W]{8,16}$/", $param['password'])) return self::setError('密码8-16位字符必须是（英文/数字/特殊符号）至少两种的组合');
                if (isset($param['password2'])) {
                    if ($param['password2'] != $param['password']) return self::setError('两次输入的密码不一致');
                    unset($param['password2']);
                }
            }
        }
        if (isset($param['safe_password'])) {
            if (!$param['safe_password']) {
                unset($param['safe_password']);
            } else {
                if (!preg_match("/^[0-9]{6}$/", $param['safe_password'])) return self::setError('安全密码请使用6位数字');
            }
        }
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = true;
        try {
            //加密得到密文和盐
            if (isset($param['password'])) {
                $param['password'] = self::getPasswordMD5($param['password']);
            }
            if (isset($param['safe_password'])) {
                $param['safe_password'] = self::getPasswordMD5($param['safe_password']);
            }

            $res1 = self::update($param);

            $res = $res && $res1 && $res2 && true;
            if ($trans) {
                self::checkTrans($res);
            }
            if (!$res1) return self::setError('更新账号失败');
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            return self::setError($e->getMessage());
        }
        if (!$res) return self::setError('更新租户失败');

        return $param;

    }

    /**找回密码 验证用户是否存在
     * @param $mobile
     * @return int
     */
    public static function memberExist($mobile)
    {
        //判断用户是否存在
        $admin = self::where('mobile', $mobile)->find();
        if ($admin) {
            return $admin['id'];
        } else {
            return 0;
        }
    }

    /**得到当前登录租户的顶级租户id和子租户id
     * @param $member_id
     */
    public static function getMemberIdAndSubMember($member_id)
    {
        $self = self::where('id', $member_id)->find();
        $member_id = $sub_member_id = 0;
        if (!$self) return compact('member_id', 'sub_member_id');
        $member_id = $self['top_id'];
        //子租户
        if ($self['parent_id'] != 0) $sub_member_id = $self['id'];
        return compact('member_id', 'sub_member_id');
    }

}
